package yz.com.javautil.sql;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Administrator
 */
public class FormatSql {

    public static void main(String[] args) {
//        updateOrSave("task_info_yz_test", "id", "'d3329bc4b4fd425d81e469f7418a7704'", null);
        Map<String, Object> dataMap = new HashMap<>(16);
        dataMap.put("id", "d3329bc4b4fd425d81e469f7418a7704");
        dataMap.put("task_name", "任务_202307071319");
        dataMap.put("telphone", "18898158122");
        dataMap.put("param", "{\"duration\":\"2\",\"level\":\"1\",\"android\":\"f039fce45146a03d\",\"version_code\":6,\"user_phone\":\"15690828827\",\"tel\":\"18898158122\"}");
        dataMap.put("task_status", 2);
        dataMap.put("create_time", "2023-07-17 10:59:14");
        update("task_info_yz_test", " where id = 'd3329bc4b4fd425d81e469f7418a7704'", dataMap);
    }

    /**
     * 根据主键判读数据唯一性并更新或保存数据
     *
     * @param tableName         表名称
     * @param primaryFieldVal   主键字段
     * @param primaryFieldWhere 主键字段的where条件
     * @param dataMap           数据
     */
    private static void updateOrSave(String tableName, String primaryFieldVal, Object primaryFieldWhere, Map<String, Object> dataMap) {
        String whereStr = " where " + primaryFieldVal + " = " + primaryFieldWhere;
        String countSql = "select count(1) from " + tableName + whereStr;
        System.out.println(countSql);
    }

    private static void save(String tableName, Map<String, Object> dataMap) {
        List<String> fieldNameList = new ArrayList<>();
        List<String> fieldValList = new ArrayList<>();
        dataMap.forEach((fieldName, fieldVal) -> {
            fieldNameList.add(fieldName);
            fieldValList.add(fieldVal.toString());
        });
        String fieldNameStr = String.join(",", fieldNameList);
        String fieldValStr = String.join("','", fieldValList);
        String insertSql = "insert into " + tableName + "( " + fieldNameStr + " ) VALUES ( '" + fieldValStr + "' )";
        System.out.println(insertSql);
    }

    private static void update(String tableName, String whereStr, Map<String, Object> dataMap) {
        List<String> fieldSetList = new ArrayList<>();
        dataMap.forEach((fieldName, fieldVal) -> {
            fieldSetList.add(fieldName + " = '" + fieldVal + "'");
        });
        String fieldSet = String.join(",", fieldSetList);
        String updateSql = "update " + tableName + " set " + fieldSet + whereStr;
        System.out.println(updateSql);
    }

}
